import { createContext, FC, memo } from "react";
import { activeTabKeyAtom, DEFAULT_TAB, workspaceTabsAtom } from "./index.tsx";
import { matchRoute } from "../../utils/tab-routes/matchRoutes.ts";
import { routes } from "../../router";
import { useAtomValue } from "jotai";
import { Button } from "@arco-design/web-react";
import { css } from "@emotion/css";
import { useAtomCallback } from "jotai/utils";

export const WorkspaceRouteParamsContext = createContext<
  Record<string, string>
>({});
export const WorkspaceRouteSearchParamsContext =
  createContext<URLSearchParams | null>(null);
export const OutletContext = createContext<any | null>(null);

const TabContent: FC<{ path: string }> = memo(({ path }) => {
  const [matchedRoutes, params, searchParams] = matchRoute(path, routes);
  if (!matchedRoutes?.handler) return null;

  return (
    <WorkspaceRouteParamsContext.Provider value={params}>
      <WorkspaceRouteSearchParamsContext.Provider value={searchParams}>
        {matchedRoutes.handler.map((route, i, arr) => {
          if (i < 2) return null;
          const next = arr[i + 1]?.element ?? null;
          return (
            <OutletContext.Provider value={next} key={route.path}>
              {route.element}
            </OutletContext.Provider>
          );
        })}
      </WorkspaceRouteSearchParamsContext.Provider>
    </WorkspaceRouteParamsContext.Provider>
  );
});

export const WorkspaceContent: FC = memo(() => {
  const tabs = useAtomValue(workspaceTabsAtom);
  const activeTabKey = useAtomValue(activeTabKeyAtom);
  const openWorkspace = useAtomCallback((_get, set) => {
    set(workspaceTabsAtom, [DEFAULT_TAB]);
  });
  if (tabs.length < 1) {
    return (
      <div
        className={css`
          display: flex;
          justify-content: center;
          align-items: center;
        `}
      >
        <Button type="primary" onClick={openWorkspace}>
          创建工作台
        </Button>
      </div>
    );
  }

  return tabs.map((tab) => (
    <div
      style={{ display: tab.key !== activeTabKey ? "none" : "block" }}
      key={tab.key}
      className={css`
        padding: 10px 20px 0 20px;
        border-radius: 6px;
        //border: 1px solid rgba(47, 43, 61, 0.16);
      `}
    >
      <TabContent path={tab.path} key={tab.key} />
    </div>
  ));
});
